<?php

/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2017/6/28
 * Time: 14:38
 */

namespace Admin\Service;

use Service\BaseService;

class CatService extends BaseService {



    public function __construct() {
        parent::__construct();
        $this->catModel = M('categories');
    }

    public function catList($name,$isPage = 1, $nowPage = 1) {

        if ($name) {
            $where['cat_name'] = array('like', '%'.$name.'%');
        }

        $obj = $this->catModel
             ->order('sort_order asc');

        if ($where) {
            $obj->where($where);
        }
        if ($isPage) {
            $countRes = $obj->count();
            self::bPage($countRes);
            return self::resReturn(200, "success", self::$pageObj);
        } else {
            $lineList = $obj->page($nowPage, self::$pageNum)->select();
            return self::resReturn(200, 'success', $lineList);
        }
    }

    public function catInfo($id) {
        return $this->catModel
            ->where('id  = '.$id)->find();
    }


    public function handleCat($data = array()){

        $act = $data['act'];
        switch ($act){

            case 'add':

                unset($data['act']);
                if(mb_strlen($data['cat_name'],'utf-8') > 6){
                    return self::resReturn(130, '分类名称长度在6个字符以内');
                }
                $data['update_time'] = time();

                $res = $this->catModel->add($data);

                break;
            case 'edit':

                unset($data['act']);
                $data['update_time'] = time();
                $res = $this->catModel->save($data);
                break;
            case 'del':
                $where['id'] = $data['id'];
                $res = $this->catModel->where($where)->delete();
                break;
        }

        if ($res){
            return self::resReturn(200, 'success');
        } else{
            return self::resReturn(130, '操作失败');
        }

    }



}
